package org.example.Window;

import org.example.algorithm.BestLifePath;
import org.example.algorithm.BestMoneyPath;
import org.example.path.Path;
import org.example.player.Player;
import org.example.treasure.Treasure;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Queue;

public class MainWindow extends JFrame implements MouseListener {


    Player player;
    static int treasureNum;
    static int pathsNum;
    public static int life; // 生命
    public static int money;  // 经济
    static int[][] treasureXY ={{70,203},{238,146},{92,351},{408,52},{459,304},         //部落地址
                                {141,428},{208,578},{633,252},{848,493},{747,146},
                                {636,461},{738,505},{536,461},{753,372},{359,548}};

    public ArrayList<Treasure> treasures = new ArrayList<Treasure>();          //部落集合

    public static JPanel playerData;    //生命和经济的数值图层
    JPanel treasurePanel;   //宝藏的图层
    JPanel playerPanel;   //玩家的图层
    public static JPanel imfPanel;     //宝藏的信息面板
    public static MessageDialog messageDialog;       //新消息提示框


    static Font font;      //字体设置1
    JButton path;   //最优路线按键
    JButton play;   //开始游戏按键
    JButton bestLife;   //最佳生命路线
    JButton bestMoney;  //最佳经济路线
    JButton back;   //回到主菜单

    public void initJFrame(){
        //初始化界面
        initFrame();
        //初始化组件，在界面中添加内容
        initView();
        //设置看见
        this.setVisible(true);
    }
    /**
     * 初始化JFrame
     */
    private void initFrame() {
        this.setSize(1280,720);
        this.setTitle("魔女之旅 吉治霖 3220608045");
        this.setResizable(false);
        this.setDefaultCloseOperation(3);//设置关闭模式
        this.setLocationRelativeTo(null);//居中
        this.setAlwaysOnTop(true);//置顶
        this.setLayout(null);//取消所有默认布局

        font = new Font("宋体", Font.BOLD,30);
        MessageDialog.owner = this;
    }


    /**
     * 绘制刚开始的游戏页面
     */
    void initView() {

        //1.添加 开始游戏 按钮
        play = new JButton(new ImageIcon("src/images/开始游戏.png"));
        play.setBounds(525,285,230,40);
        this.getContentPane().add(play);
        play.addMouseListener(this);

        //2.添加 最优路线 按钮
        path = new JButton(new ImageIcon("src/images/最优路线.png"));
        path.setBounds(525,345,230,40);
        this.getContentPane().add(path);
        path.addMouseListener(this);

        //3.添加 退出游戏 按钮
        JButton exit = new JButton(new ImageIcon("src/images/退出游戏.png"));
        exit.setBounds(525,405,230,40);
        this.getContentPane().add(exit);
        exit.addActionListener(new ActionListener() {   //给按钮添加退出事件
            @Override
            public void actionPerformed(ActionEvent e) {
                System.exit(0);
            }
        });

        //5.大logo
        JLabel LOGO = new JLabel(new ImageIcon("src/images/女勇者闯关游戏.png"));
        LOGO.setBounds(180,50,1000,225);
        this.getContentPane().add(LOGO);

        //4.添加背景
        JLabel backGround = new JLabel(new ImageIcon("src/images/初始界面背景.png"));
        backGround.setBounds(0,0,1280,720);
        this.getContentPane().add(backGround);
    }

    /**
     * 绘制最优路线页面
     */
    private void pathView() {

        //1.添加 生命最优 按钮
        bestLife = new JButton(new ImageIcon("src/images/生命最优.png"));
        bestLife.setBounds(525,285,230,40);
        this.getContentPane().add(bestLife);
        bestLife.addMouseListener(this);

        //2.添加 经济最优 按钮
        bestMoney = new JButton(new ImageIcon("src/images/经济最优.png"));
        bestMoney.setBounds(525,345,230,40);
        this.getContentPane().add(bestMoney);
        bestMoney.addMouseListener(this);

        //3.添加 返回主菜单 按钮
        back = new JButton(new ImageIcon("src/images/返回主菜单.png"));
        back.setBounds(525,405,230,40);
        this.getContentPane().add(back);
        back.addMouseListener(this);

        //5.大logo
        JLabel LOGO = new JLabel(new ImageIcon("src/images/女勇者闯关游戏.png"));
        LOGO.setBounds(180,50,1000,225);
        this.getContentPane().add(LOGO);

        //4.添加背景
        JLabel backGround = new JLabel(new ImageIcon("src/images/初始界面背景.png"));
        backGround.setBounds(0,0,1280,720);
        this.getContentPane().add(backGround);
    }

    /**
     * 绘制游戏界面
     */
    private void gameView() {
        life = 100;
        money = 0;

        //1.添加 生命 和 金币 及其数值
        playerData = new JPanel();
        playerData.setLayout(null);//取消所有默认布局
        playerData.setOpaque(false);
        playerData.setBounds(270,10,800,70);
        creatLifeAndMoney(playerData);
        this.getContentPane().add(playerData);

        //1.5 部落生成
        try {
            creatTreasure();
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        }

        //2.添加头像
        JLabel headIcon = new JLabel(new ImageIcon("src/images/头像.png"));
        headIcon.setBounds(20,10,50,50);
        this.getContentPane().add(headIcon);
        JLabel headName = new JLabel("伊雷娜");
        headName.setFont(font);
        headName.setForeground(Color.WHITE);
        headName.setBounds(80,10,140,50);
        this.getContentPane().add(headName);

        //3.添加魔女
        player = new Player();
        Player.route.clear();
        playerPanel = new JPanel();
        Player.jPanel = playerPanel;
        playerPanel.setBounds(0,0,1280,720);
        playerPanel.setOpaque(false);
        playerPanel.setLayout(null);//取消所有默认布局
        playerPanel.add(player);
        this.getContentPane().add(playerPanel);


        //3.5添加返回按钮
        back = new JButton(new ImageIcon("src/images/返回主菜单.png"));
        back.setBounds(1000,15,230,40);
        this.getContentPane().add(back);
        back.addMouseListener(this);

        //4.添加信息界面
        imfPanel = new JPanel();
        imfPanel.setLayout(null);//取消所有默认布局
        imfPanel.setOpaque(false);
        imfPanel.setBounds(980,70,285,610);
        creatImf(imfPanel,Player.current);
        this.getContentPane().add(imfPanel);


        //5.添加背景
        JLabel backGroundAside = new JLabel(new ImageIcon("src/images/信息卷轴.png"));
        backGroundAside.setBounds(980,70,285,610);
        this.getContentPane().add(backGroundAside);
        JLabel backGroundTop = new JLabel(new ImageIcon("src/images/上边框.png"));
        backGroundTop.setBounds(0,0,1280,70);
        this.getContentPane().add(backGroundTop);
        ImageIcon image = new ImageIcon("src/images/游戏地图.png");
        JLabel backGround = new JLabel(image);
        backGround.setBounds(0,65,image.getIconWidth(),image.getIconHeight());
        this.getContentPane().add(backGround);
    }
    /**
     * 绘制游戏答案界面
     */
    private void bestPathView(Boolean isLife) {
        life = 100;
        money = 0;

        //1.添加 生命 和 金币 及其数值
        playerData = new JPanel();
        playerData.setLayout(null);//取消所有默认布局
        playerData.setOpaque(false);
        playerData.setBounds(270,10,800,70);
        creatLifeAndMoney(playerData);
        this.getContentPane().add(playerData);

        //1.5 部落生成
        try {
            creatTreasureAns();
            if (isLife){
                new BestLifePath(this.treasures,this.treasures.get(0));
            }else {
                new BestMoneyPath(this.treasures,this.treasures.get(0));
            }
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        }

        //2.添加头像
        JLabel headIcon = new JLabel(new ImageIcon("src/images/头像.png"));
        headIcon.setBounds(20,10,50,50);
        this.getContentPane().add(headIcon);
        JLabel headName = new JLabel("伊雷娜");
        headName.setFont(font);
        headName.setForeground(Color.WHITE);
        headName.setBounds(80,10,140,50);
        this.getContentPane().add(headName);

        //3.添加魔女
        player = new Player();
        System.out.println(Player.current.getName()+"你好");
        playerPanel = new JPanel();
        Player.jPanel = playerPanel;
        playerPanel.setBounds(0,0,1280,720);
        playerPanel.setOpaque(false);
        playerPanel.setLayout(null);//取消所有默认布局
        playerPanel.add(player);
        this.getContentPane().add(playerPanel);


        //3.5添加返回按钮
        back = new JButton(new ImageIcon("src/images/返回主菜单.png"));
        back.setBounds(1000,15,230,40);
        this.getContentPane().add(back);
        back.addMouseListener(this);

        //4.添加步骤(新信息)界面
        imfPanel = new JPanel();
        imfPanel.setLayout(null);//取消所有默认布局
        imfPanel.setOpaque(false);
        imfPanel.setBounds(980,70,285,610);
        creatImfAns(imfPanel,treasures.get(treasures.size() - 1));
        this.getContentPane().add(imfPanel);


        //5.添加背景
        JLabel backGroundAside = new JLabel(new ImageIcon("src/images/信息卷轴.png"));
        backGroundAside.setBounds(980,70,285,610);
        this.getContentPane().add(backGroundAside);
        JLabel backGroundTop = new JLabel(new ImageIcon("src/images/上边框.png"));
        backGroundTop.setBounds(0,0,1280,70);
        this.getContentPane().add(backGroundTop);
        ImageIcon image = new ImageIcon("src/images/游戏地图.png");
        JLabel backGround = new JLabel(image);
        backGround.setBounds(0,65,image.getIconWidth(),image.getIconHeight());
        this.getContentPane().add(backGround);
    }



    void clearAll() {
        this.getContentPane().removeAll();
        this.getContentPane().revalidate();
        this.getContentPane().repaint();
    }

    /**
     * 部落 和 路径 生成函数
     */
    private void creatTreasure() throws IOException {
        String mapUrl = "src/map.txt";
        BufferedReader reader = new BufferedReader(new FileReader(mapUrl));
        String[] nums = reader.readLine().split(" ");
        treasureNum = Integer.parseInt(nums[0]);
        pathsNum = Integer.parseInt(nums[1]);

        //创建城堡图层
        treasurePanel = new JPanel();
        treasurePanel.setBounds(0,0,1280,720);
        treasurePanel.setOpaque(false);
        treasurePanel.setLayout(null);//取消所有默认布局
        for (int i = 0; i < treasureNum; i++) {
            nums = reader.readLine().split(" ");
            int[] XY = treasureXY[i];
            Treasure treasure = new Treasure(XY[0],XY[1],nums[0],Integer.parseInt(nums[1]),nums[2]);
            treasure.setDescription(nums[3]);
            if (i == 0){    //给魔女添加首坐标
                Player.current = treasure;
            } else if (i == treasureNum - 1) {
                treasure.setIcon(new ImageIcon("src/main/java/org/example/treasure/魔王堡.png"));
            }
            treasures.add(treasure);
            treasurePanel.add(treasure);
           //添加部落名字
            JLabel name = new JLabel("<html>"+nums[2]+"</html>");
            name.setFont(new Font(null,Font.BOLD,12));
            name.setBounds(XY[0] + 20,XY[1] + 65,80,20);
            treasurePanel.add(name);

        }
        this.getContentPane().add(treasurePanel);

        Path path;
        char to;
        for (int i = 0; i < pathsNum; i++) {
            nums = reader.readLine().split(" ");
            to = (char) (Integer.parseInt(nums[1])+'A');
            path = new Path(String.valueOf(to),Integer.parseInt(nums[2]));
            treasures.get(Integer.parseInt(nums[0])).addPath(path);
            to = (char) (Integer.parseInt(nums[0])+'A');
            path = new Path(String.valueOf(to),Integer.parseInt(nums[2]));
            treasures.get(Integer.parseInt(nums[1])).addPath(path);
        }

    }
    private void creatTreasureAns() throws IOException {
        String mapUrl = "src/map.txt";
        BufferedReader reader = new BufferedReader(new FileReader(mapUrl));
        String[] nums = reader.readLine().split(" ");
        treasureNum = Integer.parseInt(nums[0]);
        pathsNum = Integer.parseInt(nums[1]);

        //创建城堡图层
        treasurePanel = new JPanel();
        treasurePanel.setBounds(0,0,1280,720);
        treasurePanel.setOpaque(false);
        treasurePanel.setLayout(null);//取消所有默认布局
        for (int i = 0; i < treasureNum; i++) {
            nums = reader.readLine().split(" ");
            int[] XY = treasureXY[i];
            Treasure treasure = new Treasure(XY[0],XY[1],nums[0],Integer.parseInt(nums[1]),nums[2],true);
            treasure.setDescription(nums[3]);
            //首和尾要单独处理
            if (i == 0){
                Player.current = treasure;  //给魔女添加首坐标
            } else if (i == treasureNum - 1) {
                treasure.setIcon(new ImageIcon("src/main/java/org/example/treasure/魔王堡.png"));
            }
            treasures.add(treasure);
            treasurePanel.add(treasure);
            //添加部落名字
            JLabel name = new JLabel("<html>"+nums[2]+"</html>");
            name.setFont(new Font(null,Font.BOLD,12));
            name.setBounds(XY[0] + 20,XY[1] + 65,80,20);
            treasurePanel.add(name);

        }
        this.getContentPane().add(treasurePanel);

        Path path;
        char to;
        for (int i = 0; i < pathsNum; i++) {
            nums = reader.readLine().split(" ");
            to = (char) (Integer.parseInt(nums[1])+'A');
            path = new Path(String.valueOf(to),Integer.parseInt(nums[2]));
            treasures.get(Integer.parseInt(nums[0])).addPath(path);
            to = (char) (Integer.parseInt(nums[0])+'A');
            path = new Path(String.valueOf(to),Integer.parseInt(nums[2]));
            treasures.get(Integer.parseInt(nums[1])).addPath(path);
        }

    }

    /**
     * 生成生命和金币
     */
    public static void creatLifeAndMoney(JPanel data) {
        JLabel lifeIcon = new JLabel(new ImageIcon("src/images/生命.png"));
        lifeIcon.setBounds(100,0,50,50);
        JLabel lifeData = new JLabel(life+"");
        lifeData.setForeground(Color.WHITE);
        lifeData.setFont(font);
        lifeData.setBounds(170,0,120,50);
        data.add(lifeData);
        data.add(lifeIcon);
        System.out.println(life + money + "");

        JLabel moneyIcon = new JLabel(new ImageIcon("src/images/金币.png"));
        moneyIcon.setBounds(400,0,50,50);
        JLabel moneyData = new JLabel(money+"");
        moneyData.setForeground(Color.WHITE);
        moneyData.setFont(font);
        moneyData.setBounds(470,0,120,50);
        data.add(moneyData);
        data.add(moneyIcon);
    }

    /**
     * 生成部落右侧信息
     */
    public static void creatImf(JPanel imf,Treasure treasure) {
        //生成部落名称
        JLabel treasureName = new JLabel(treasure.name);
        treasureName.setForeground(Color.BLACK);
        treasureName.setFont(font);
        if (treasure.name.length() >= 5){
            treasureName.setBounds(75,230,200,50);
        }else {
            treasureName.setBounds(105,230,200,50);
        }
        imf.add(treasureName);

        //部落照片生成
        JLabel treasureIcon = new JLabel(treasure.getIconImage());
        treasureIcon.setBounds(80,50,135,180);
        imf.add(treasureIcon);

        //生成部落简介
        Font fontDe = new Font(null,Font.BOLD,15);
        JLabel treasureDe = new JLabel("<html>"+treasure.description+"</html>");
        treasureDe.setForeground(Color.BLACK);
        treasureDe.setFont(fontDe);
        treasureDe.setBounds(70,260,170,250);
        imf.add(treasureDe);

        //生成价值和伤害
        JLabel treasureValueAndDamage;
        Treasure cur = Player.current;
        fontDe = new Font(null,Font.BOLD,20);
        for (Path path : cur.getPaths()) {
//            System.out.println("一个路径终点:"+path.to);
            if (path.to.equals(treasure.ID)){
                treasureValueAndDamage = new JLabel("<html>价值: "+treasure.value + "  危险值: " +path.damage+"</html>");
                treasureValueAndDamage.setForeground(Color.BLACK);
                treasureValueAndDamage.setFont(fontDe);
                treasureValueAndDamage.setBounds(45,520,300,50);
                imf.add(treasureValueAndDamage);
                return;
            }
        }
        treasureValueAndDamage = new JLabel("<html>价值:"+treasure.value+" 无法直接到达"+"</html>");
        treasureValueAndDamage.setForeground(Color.BLACK);
        treasureValueAndDamage.setFont(fontDe);
        treasureValueAndDamage.setBounds(45,520,300,50);
        imf.add(treasureValueAndDamage);

    }//游戏界面的信息
    public static void creatImfAns(JPanel imf,Treasure treasure) {
        //那到生命最佳路线答案
        ArrayList<Treasure> route = treasure.route;
        route.add(treasure);
        JButton last = new JButton("上一步");
        JButton next = new JButton("下一步");
        ActionListener actionListener = new ActionListener(){

            int step = 0;
            int index;
            int[] needIndex;
            Treasure deal;
            @Override
            public void actionPerformed(ActionEvent e) {
                if (e.getSource() == last) {
                    if (step > 0) {
                        deal = route.get(--step);
                        index = deal.ID.charAt(0) - 'A';
                        needIndex = treasureXY[index];



                        Player.jPanel.removeAll();
                        Player.jPanel.revalidate();
                        Player.jPanel.repaint();

                        Player player = new Player();
                        player.setBounds(needIndex[0] - 40,needIndex[1] - 10,75,50);
                        Player.jPanel.add(player);

                        //更新生命和经济数值
                        playerData.removeAll();
                        playerData.revalidate();
                        playerData.repaint();
//                        处理生命 和 经济
                        Treasure a = route.get(step + 1);
                        for (Path path : deal.getPaths()) {
                            if (path.to.equals(a.ID)) {
                                if (path.damage != 2){
                                    life += path.damage;
                                }
                                if(a.isVisible && a.visitedNum == 1){
                                    money -= a.value;
                                    a.isVisible = false;
                                }
                                a.visitedNum --;
                            }
                        }
                        creatLifeAndMoney(playerData);
                    }
                } else if (e.getSource() == next) {
                    if (step < route.size() - 1) {
                        deal = route.get(++step);
                        index = deal.ID.charAt(0) - 'A';
                        needIndex = treasureXY[index];


                        Player.jPanel.removeAll();
                        Player.jPanel.revalidate();
                        Player.jPanel.repaint();

                        Player player = new Player();
                        player.setBounds(needIndex[0] - 40,needIndex[1] - 10,75,50);
                        Player.jPanel.add(player);

                        //更新生命和经济数值
                        playerData.removeAll();
                        playerData.revalidate();
                        playerData.repaint();
//                        处理生命 和 经济
                        for (Path path : route.get(step - 1).getPaths()) {
                            if (path.to.equals(deal.ID)) {
                                if (path.damage != 2){
                                    life -= path.damage;
                                }
                                if (!deal.isVisible){
                                    money += deal.value;
                                    deal.isVisible = true;
                                }
                                deal.visitedNum++;
                            }
                        }
                        creatLifeAndMoney(playerData);
                    }
                }
            }
        };
        //上一步按钮
        last.setFont(new Font(null,0,20));
        last.setContentAreaFilled(false);
        last.setBounds(80,455,140,50);

        last.addActionListener(actionListener);
        imf.add(last);
        //下一步按钮
        next.setFont(new Font(null,0,20));
        next.setContentAreaFilled(false);
        next.setBounds(80,515,140,50);
        next.addActionListener(actionListener);
        imf.add(next);
        //生成路径信息
        for (int i = 0; i < route.size(); i++) {
            JLabel stepImf = new JLabel("<html>第 " + i + "步："+ route.get(i).name + "</html>");
            stepImf.setFont(new Font(null,0,20));
            stepImf.setBounds(45,50+i*25,200,30);
            imf.add(stepImf);
//            System.out.println("添加成功");
        }

        //生成价值和伤害


    }//答案界面的信息



    @Override
    public void mouseClicked(MouseEvent e) {
        if (e.getSource() == play){ //开始游戏
            clearAll();
            gameView();



        } else if (e.getSource() == path) { //最佳路线
            clearAll();
            pathView();

        }else if (e.getSource() == bestLife) { //最佳生命路线
            clearAll();
            bestPathView(true);

        }else if (e.getSource() == bestMoney) { //最佳经济路线
            clearAll();
            bestPathView(false);

        }else if (e.getSource() == back) { //返回主菜单
            clearAll();
            initView();
            if (!treasures.isEmpty()){
                treasures.clear();
            }
        }
    }
    @Override
    public void mousePressed(MouseEvent e) {

    }

    @Override
    public void mouseReleased(MouseEvent e) {

    }

    @Override
    public void mouseEntered(MouseEvent e) {

    }

    @Override
    public void mouseExited(MouseEvent e) {

    }
}
